package com.css.zfzx.sjcj.modules.hddcGeoGeomorphySvyPoint.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.superRepository.SuperRepository;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB1GeologySvyProjectTable.repository.entity.HddcB1GeologysvyprojecttableEntity;
import com.css.zfzx.sjcj.modules.hddcB1GeomorLnOnFractBlt.repository.entity.HddcB1GeomorlnonfractbltEntity;
import com.css.zfzx.sjcj.modules.hddcB1GeomorLnOnFractBlt.viewobjects.HddcB1GeomorlnonfractbltVO;
import com.css.zfzx.sjcj.modules.hddcGeoGeomorphySvyPoint.repository.HddcGeogeomorphysvypointNativeRepository;
import com.css.zfzx.sjcj.modules.hddcGeoGeomorphySvyPoint.repository.HddcGeogeomorphysvypointRepository;
import com.css.zfzx.sjcj.modules.hddcGeoGeomorphySvyPoint.repository.entity.HddcGeogeomorphysvypointEntity;
import com.css.zfzx.sjcj.modules.hddcGeoGeomorphySvyPoint.service.HddcGeogeomorphysvypointService;
import com.css.zfzx.sjcj.modules.hddcGeoGeomorphySvyPoint.viewobjects.HddcGeogeomorphysvypointQueryParams;
import com.css.zfzx.sjcj.modules.hddcGeoGeomorphySvyPoint.viewobjects.HddcGeogeomorphysvypointVO;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPoint.repository.entity.HddcGeologicalsvypointEntity;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPoint.service.HddcGeologicalsvypointService;
import com.css.zfzx.sjcj.modules.hddcTargetRegion.repository.entity.HddcTargetregionEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author lihelei
 * @date 2020-11-26
 */
@Service
public class HddcGeogeomorphysvypointServiceImpl implements HddcGeogeomorphysvypointService {

	@Autowired
    private HddcGeogeomorphysvypointRepository hddcGeogeomorphysvypointRepository;
    @Autowired
    private HddcGeogeomorphysvypointNativeRepository hddcGeogeomorphysvypointNativeRepository;
    @Autowired
    private HddcGeologicalsvypointService hddcGeologicalsvypointService;

    @Override
    public JSONObject queryHddcGeogeomorphysvypoints(HddcGeogeomorphysvypointQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcGeogeomorphysvypointEntity> hddcGeogeomorphysvypointPage = this.hddcGeogeomorphysvypointNativeRepository.queryHddcGeogeomorphysvypoints(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcGeogeomorphysvypointPage);
        return jsonObject;
    }


    @Override
    public HddcGeogeomorphysvypointEntity getHddcGeogeomorphysvypoint(String id) {
        HddcGeogeomorphysvypointEntity hddcGeogeomorphysvypoint = this.hddcGeogeomorphysvypointRepository.findById(id).orElse(null);
         return hddcGeogeomorphysvypoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeogeomorphysvypointEntity saveHddcGeogeomorphysvypoint(HddcGeogeomorphysvypointEntity hddcGeogeomorphysvypoint) {
        String uuid = UUIDGenerator.getUUID();
        hddcGeogeomorphysvypoint.setUuid(uuid);
        hddcGeogeomorphysvypoint.setQualityinspectionStatus("0");
        hddcGeogeomorphysvypoint.setCreateUser(PlatformSessionUtils.getUserId());
        hddcGeogeomorphysvypoint.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcGeogeomorphysvypoint.setIsValid("1");
        this.hddcGeogeomorphysvypointRepository.save(hddcGeogeomorphysvypoint);
        return hddcGeogeomorphysvypoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeogeomorphysvypointEntity updateHddcGeogeomorphysvypoint(HddcGeogeomorphysvypointEntity hddcGeogeomorphysvypoint) {
        UpdateUtil.copyNullProperties(hddcGeogeomorphysvypointRepository.findByUuidAndIsValid(hddcGeogeomorphysvypoint.getUuid(), "1"), hddcGeogeomorphysvypoint);
        hddcGeogeomorphysvypoint.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcGeogeomorphysvypoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcGeogeomorphysvypointRepository.save(hddcGeogeomorphysvypoint);
        return hddcGeogeomorphysvypoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcGeogeomorphysvypoints(List<String> ids) {
        List<HddcGeogeomorphysvypointEntity> hddcGeogeomorphysvypointList = this.hddcGeogeomorphysvypointRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcGeogeomorphysvypointList) && hddcGeogeomorphysvypointList.size() > 0) {
            for(HddcGeogeomorphysvypointEntity hddcGeogeomorphysvypoint : hddcGeogeomorphysvypointList) {
                hddcGeogeomorphysvypoint.setIsValid("0");
                hddcGeogeomorphysvypoint.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeogeomorphysvypoint.setUpdateTime(new Date());
                this.hddcGeogeomorphysvypointRepository.save(hddcGeogeomorphysvypoint);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcGeogeomorphysvypointQueryParams queryParams, HttpServletResponse response) {
        List<HddcGeogeomorphysvypointEntity> yhDisasterEntities = hddcGeogeomorphysvypointNativeRepository.exportYhDisasters(queryParams);
        List<HddcGeogeomorphysvypointVO> list=new ArrayList<>();
        for (HddcGeogeomorphysvypointEntity entity:yhDisasterEntities) {
            HddcGeogeomorphysvypointVO yhDisasterVO=new HddcGeogeomorphysvypointVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"地质地貌调查观测点-点","地质地貌调查观测点-点",HddcGeogeomorphysvypointVO.class,"地质地貌调查观测点-点.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcGeogeomorphysvypointVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcGeogeomorphysvypointVO.class, params);
            List<HddcGeogeomorphysvypointVO> list = result.getList();
            // Excel条数据
            //int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcGeogeomorphysvypointVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcGeogeomorphysvypointVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    @Autowired
    SuperRepository superRepository;
    @Transactional
    @Override
    public int dataQualityCheck() {
        List<HddcGeogeomorphysvypointEntity> listAll = hddcGeogeomorphysvypointRepository.findByAll();
        List<HddcGeogeomorphysvypointEntity> updateList=new ArrayList<>();
        for (HddcGeogeomorphysvypointEntity b2All: listAll) {
            String str="";
            if (StringUtils.isEmpty(b2All.getGeologicalsvypointid())) {
                str += "【地质地貌调查观测点】中的地质调查观测点编号为空。";
            }else {
                HddcGeologicalsvypointEntity hddcGeologicalsvypointEntity = hddcGeologicalsvypointService.findbyId(b2All.getGeologicalsvypointid());
                if (hddcGeologicalsvypointEntity == null) {
                    str += "【地质地貌调查观测点】表单中的编号与【地质调查观测点】中的地质调查观测点编号不一致。";
                }else {
                    if (StringUtils.isEmpty(b2All.getFieldid())){
                        str += "【地质地貌调查观测点】观测点野外编号为空。";
                    }else {
                        if (!(b2All.getFieldid().equals(hddcGeologicalsvypointEntity.getFieldid()))) {
                            str += "【地质地貌调查观测点】表单中的观测点野外编号与【地质调查观测点】中的观测点野外编号不一致。";
                        }
                    }
                }
            }
            if(str.isEmpty()){
                str +="【地质地貌调查观测点】与【地质调查观测点】质检成功。";
                b2All.setQualityinspectionStatus("1");
            }else{
                b2All.setQualityinspectionStatus("2");
            }
            b2All.setQualityinspectionComments(null);
            String[] split = str.split("。");
            for (int i = 0; i < split.length; i++) {
                if (i == 0) {
                    b2All.setExtends1(split[i]);
                    b2All.setExtends2(null);
                    b2All.setExtends3(null);
                } else if (i == 1) {
                    b2All.setExtends2(split[i]);
                    b2All.setExtends3(null);
                } else if (i == 2) {
                    b2All.setExtends3(split[i]);
                }
            }
            updateList.add(b2All);
        }
        superRepository.batchUpdate(updateList);
        return 1;
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList(List<HddcGeogeomorphysvypointVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcGeogeomorphysvypointEntity yhDisasterEntity = new HddcGeogeomorphysvypointEntity();
            HddcGeogeomorphysvypointVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcGeogeomorphysvypoint(yhDisasterEntity);
        }
    }

}
